<?php

/**
 * Config logic.
 *
 * @category Zend
 * @package Disputeo
 * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc.
 * @version $Id$
 * @link http://framework.zend.com
 * @since Available since release 1.0
 * @license GPL v3
 */
class Disputeo_Config extends Zend_Config
{
    /**
     * @var Disputeo_Config
     */
    protected static $_instance;

    /**
     * @var Disputeo_Cache
     */
    protected $_cache;

    /**
     * @var string
     */
    protected $_configPath;

    /**
     * @var array
     */
    protected $_files = array(
        'disputeo.ini',
        'application.ini'
    );

    /**
     * Zend_Config provides a property based interface to
     * an array. The data are read-only unless $allowModifications
     * is set to true on construction.
     *
     * Zend_Config also implements Countable and Iterator to
     * facilitate easy access to the data.
     *
     * @param  array   $array
     * @param  boolean $allowModifications
     * @return void
     */
    public function __construct(array $array, $allowModifications = false)
    {
        parent::__construct($array, $allowModifications);

        $this->_allowModifications = true;
        $this->_configPath = APPLICATION_PATH . DIRECTORY_SEPARATOR
            . 'configs' . DIRECTORY_SEPARATOR;

        foreach ($this->_files as $file) {
            $this->merge($this->_getConfig($file));
        }
    }

    /**
     * Set cache
     * 
     * @param Disputeo_Cache $cache
     */
    public function setCache(Disputeo_Cache $cache)
    {
        $this->_cache = $cache;

        return $this;
    }

    /**
     * Get the application environment
     * 
     * @return string
     */
    protected function _getEnv()
    {
        return isset($_SERVER['APPLICATION_ENV']) ? $_SERVER['APPLICATION_ENV'] : 'production';
    }

    /**
     * Create config object or get from cache
     * 
     * @param string $file
     * @return \Zend_Config_Ini
     */
    protected function _getConfig($file)
    {
        $configPath = $this->_configPath . $file;
        $env = $this->_getEnv();

        if ($this->_cache) {
            $configName = basename($configPath);
            $config = $this->_cache->load($configName);
            if (!$config) {
                $config = new Zend_Config_Ini($configPath, $env);
                $this->_cache->save($config, $configName);
            }
        } else {
            $config = new Zend_Config_Ini($configPath, $env);
        }

        return $config;
    }

    /**
     * Get config singleton
     * 
     * @param Zend_Cache $cache
     * @return Zend_Config
     */
    public static function config($cache = null)
    {
        if (!self::$_instance) {
            $config = new self(array());
            if ($cache) {
                $config->setCache($cache);
            }
            
            self::$_instance = $config;
        }

        return self::$_instance;
    }

}